// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VelocityOverrideAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Navigation.Runtime.Motion
{
    using System;
    using System.Runtime.Serialization;
    using Microsoft.Robotics.Interaction.Runtime.Input;
    using Microsoft.Robotics.Navigation.Motion;
    using Microsoft.Robotics.Navigation.Runtime.Motion;
    using Microsoft.Robotics.Navigation.Runtime.Perception;
    using Microsoft.Robotics.Runtime;

    /// <summary>
    /// Implements manual drive with gamepad override
    /// </summary>
    [DataContract]
    public class VelocityOverrideAgent : ConsumerProducerAgent<MobileBaseVelocityReferenceMessage, MobileBaseVelocityReferenceMessage>, 
                                    ISubscriptionReceiver<GamePadAgentMessage>
    {
        /// <summary>
        /// object for converting game pad message to mobile base velocity messages 
        /// </summary>
        private VelocityFromGamePad velocityOverride;

        /// <summary>
        /// Name of the agent producing the game pad messages
        /// </summary>
        [DataMember(Name = "GamePadProducer")]
        private string gamePadProducer = default(string);

        /// <summary>
        /// Speed to travel when moving forward
        /// </summary>
        [DataMember(Name = "MaximumSpeedInMetersPerSecond")]
        private double maxSpeedInMetersPerSecond = default(double);

        /// <summary>
        /// Turning speed
        /// </summary>
        [DataMember(Name = "MaximumTurnRateInRadiansPerSecond")]
        private double maxTurnRateInRadiansPerSecond = default(double);

        /// <summary>
        /// Maximum amount of time to turn for
        /// </summary>
        [DataMember(Name = "MaximumTurnDurationInMs")]
        private double maximumTurnDurationInMs = default(double);

        /// <summary>
        /// Minimum amount of time to turn for
        /// </summary>
        [DataMember(Name = "MinimumTurnDurationInMs")]
        private double minimumTurnDurationInMs = default(double);

        /// <summary>
        /// Agent producing the forward path clear indication
        /// </summary>
        private IAgentHost gamePadAgent;

        /// <summary>
        /// Turn override on or off (when off velocity messages are passed through)
        /// </summary>
        private bool overrideOn = false;

        /// <summary>
        /// Initializes a new instance of the VelocityOverrideAgent class
        /// </summary>
        /// <param name="name">The agent name</param>
        /// <param name="gamePadProducer">The game pad producer name</param>\
        /// <param name="velocityProducer">The mobile base velocity reference message producer</param>
        /// <param name="maxSpeedInMetersPerSecond">Speed to travel when moving forward</param>
        /// <param name="maxTurnRateInRadiansPerSecond">Turning speed</param>
        /// <param name="maximumTurnDurationInMs">Maximum amount of time to turn for</param>
        /// <param name="minimumTurnDurationInMs">Minimum amount of time to turn for</param>
        public VelocityOverrideAgent(
            string name, 
            IProducer<GamePadAgentMessage> gamePadProducer, 
            IProducer<MobileBaseVelocityReferenceMessage> velocityProducer,
            double maxSpeedInMetersPerSecond, 
            double maxTurnRateInRadiansPerSecond, 
            double maximumTurnDurationInMs, 
            double minimumTurnDurationInMs)
            : base(name, velocityProducer.Name)
        {
            this.gamePadProducer = gamePadProducer.Name;
            this.maxSpeedInMetersPerSecond = maxSpeedInMetersPerSecond;
            this.maxTurnRateInRadiansPerSecond = maxTurnRateInRadiansPerSecond;
            this.maximumTurnDurationInMs = maximumTurnDurationInMs;
            this.minimumTurnDurationInMs = minimumTurnDurationInMs;
        }

        /// <summary>
        /// Called on agent initialization
        /// </summary>
        /// <param name="locator">The agent locator.</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);
            this.gamePadAgent = this.Locator.GetAgent(this.gamePadProducer);

            this.velocityOverride = new VelocityFromGamePad(this.maxSpeedInMetersPerSecond, this.maxTurnRateInRadiansPerSecond, this.maximumTurnDurationInMs, this.minimumTurnDurationInMs);
        }

        /// <summary>
        /// Called when the agent is activated
        /// </summary>
        public override void OnActivated()
        {
            base.OnActivated();

            if (this.gamePadAgent != null)
            {
                this.gamePadAgent.Subscribe<GamePadAgentMessage>(this);
                this.gamePadAgent.Activate();
            }
        }

        /// <summary>
        /// Handle MobileBaseVelocity messages
        /// </summary>
        /// <param name="message">Message with game pad state</param>
        public override void Receive(MobileBaseVelocityReferenceMessage message)
        {
            if (this.overrideOn)
            {
                return;
            }

            this.Publisher.Post(message);
        }

        /// <summary>
        /// Handle game pad agent message
        /// </summary>
        /// <param name="message">Message with game pad state</param>
        public void Receive(GamePadAgentMessage message)
        {
            // only override while A button is pressed
            if (message.Buttons != null && message.Buttons.A)
            {
                this.overrideOn = true;
            }
            else
            {
                this.overrideOn = false;
                return;
            }

            this.Publisher.Post(this.velocityOverride.CreateMobileBaseVelocityReferenceMessage(message));
        }
    }
}
